﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace TeF.Runner.Services
{
    internal class ReportCreator : IReportCreator
    {
        public string CreateReport(string reportDirectoryPath, IEnumerable<ITestAssembly> testAssemblies)
        {
            if (string.IsNullOrEmpty(reportDirectoryPath))
                throw new ArgumentException("reportDirectoryPath");
            if (!Directory.Exists(reportDirectoryPath))
                throw new ArgumentException("reportDirectoryPath");

            var xmlDocument =
                new XDocument(
                    new XElement("TeF_Report",
                    testAssemblies.Select(testAssembly => 
                        new XElement("TestAssembly",
                            new XAttribute("name", testAssembly.Name),
                            new XAttribute("state", testAssembly.State),    
                            testAssembly.Namespaces.Select(testNamespace =>
                                new XElement("TestNamespace",
                                    new XAttribute("name", testNamespace.Name),
                                    new XAttribute("state", testNamespace.State),   
                                    testNamespace.Containers.Select(testContainer =>
                                        new XElement("TestContainer",
                                            new XAttribute("name", testContainer.Name),
                                            new XAttribute("state", testContainer.State),   
                                            testContainer.Tests.Select(test =>
                                                new XElement("Test",
                                                new XAttribute("name", test.Name),
                                                new XAttribute("state", test.State), 
                                                new XElement("Log", test.Log)))))))))));
            
            var reportFileName = GetReportFileName();
            var reportFilePath = Path.Combine(reportDirectoryPath, reportFileName);

            xmlDocument.Save(reportFilePath);

            return reportFilePath;
        }

        private static string GetReportFileName()
        {
            var now = IoCHelper.Container.Get<ISystemDateTime>().Now;

            return
                string.Format(
                    "TeF_Report_{0}_{1}_{2}_{3}_{4}_{5}.xml",
                    now.Year.ToString("0000"),
                    now.Month.ToString("00"),
                    now.Day.ToString("00"),
                    now.Hour.ToString("00"),
                    now.Minute.ToString("00"),
                    now.Second.ToString("00"));
        }
    }
}
